package com.robusta.app.auth.model;

import com.robusta.app.model.persistence.AuditListener;
import com.robusta.app.model.persistence.Creatable;
import com.robusta.app.model.persistence.Updatable;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "USER_SESSIONS") @EntityListeners(AuditListener.class)
public class UserSessionModel extends com.robusta.app.model.persistence.Entity implements Serializable, Creatable, Updatable {
    @Id
    @Column(name = "SESSION_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "AUTH_TOKEN", nullable = false)
    private String token;
    @OneToOne
    @JoinColumn(name="USER_ID", nullable=false, updatable=false)
    private UserModel loggedInUser;
    @Column(name = "ACTIVE", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private Status status;
    @Column(name = "VALIDITY", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date validity;

    public UserSessionModel(String token, UserModel loggedInUser) {
        this(null, token, new Date(System.currentTimeMillis() + (1000 * 60 * 30)), loggedInUser);
    }

    public enum Status {
        ACTIVE("Y"), INACTIVE("N");
        private String status;

        Status(String status) {
            this.status = status;
        }

        @Override
        public String toString() {
            return status;
        }
    }

    public UserSessionModel() {} // for JPA.



    public UserSessionModel(Long id, String token, Date validity, UserModel userModel) {
        this.id = id;
        this.token = token;
        this.validity = validity;
        this.status = Status.ACTIVE;
        this.loggedInUser = userModel;
    }

    public void invalidate() {
        this.status = Status.INACTIVE;
    }

    public Long getId() {
        return id;
    }

    public String getToken() {
        return token;
    }

    public UserModel getLoggedInUser() {
        return loggedInUser;
    }

    public Date getValidity() {
        return validity;
    }
}
